/*
 * main.c
 *
 *  Created on: 13.10.2012
 *      Author: md5sum@alexsp.ru
 */


#include "global.h"
#include "times.h"
#include "ds1820.h"
#include "disp_key.h"
#include "m41t81.h"
#include <avr/interrupt.h>
#include <avr/pgmspace.h>

volatile uint8_t sec_flag=0;
const prog_char initializing_str[]="Initializing...";

int main() {
	//	hw_ret_status err=SUCCESS;
	read_config();
	display_init();
	display_clear();
	time_init();
	sei();

	display_xy(0,0);
	display_str_p((prog_char *)initializing_str);
	display_flush();

	while (sec_flag==0);
	sec_flag=0;
	room_last_err=ds1820_start(ROOM);
	heater_last_err=ds1820_start(HEATER);
	radiator_last_err=ds1820_start(RADIATOR);
	while (sec_flag==0);
	sec_flag=0;
	time_read(&current_time);
	if (flags&&FLG_PWR_ERR) {
		last_pow_off_time=current_time;
		time_read(&current_time);
	}
	current_temp=get_termo_for_time(current_time.ten_m,current_time.day_w);
	next_time=get_next_times(&current_time);
	next_temp=get_termo_for_time(next_time,current_time.day_w);
	for (;;) {
		/*Примерно раз в милисек выполняем обновление экрана*/
		if (TIFR&(1<<OCF2)) {
			TIFR|=(1<<OCF2);
			PORTD^=(1<<PD7);
			disp_step();
		}

		if (sec_flag) {
			sec_flag--;
			current_time.sec++;
			if (current_time.sec>59) {
				time_read(&current_time);
				if (main_status&STATUS_USER_T) {
					user_time--;
					if (!user_time) {
						//TODO end user setting
					}
				}
			}

			if (!(main_status&STATUS_DS_ERR)) {
				if (room_last_err==SUCCESS) {
					if (ds1820_get_temp(ROOM,&room_temp)==SUCCESS) {
						room_temp>>=1;
						room_err_cnt=0;
					}else{room_err_cnt++;}
				}else{room_err_cnt++;}

				if (heater_last_err==SUCCESS) {
					if (ds1820_get_temp(HEATER,&heater_temp)==SUCCESS) {
						heater_temp>>=1;
						heater_err_cnt=0;
					}else{heater_err_cnt++;}
				}else{heater_err_cnt++;}

				if (radiator_last_err==SUCCESS) {
					if (ds1820_get_temp(RADIATOR,&radiator_temp)==SUCCESS) {
						radiator_temp>>=1;
						radiator_err_cnt=0;
					}else{radiator_err_cnt++;}
				}else{radiator_err_cnt++;}

				if (room_err_cnt>MAX_DS_ERROR) {main_status|=STATUS_DS_ERR;}
				if (heater_err_cnt>MAX_DS_ERROR) {main_status|=STATUS_DS_ERR;}
				if (radiator_err_cnt>MAX_DS_ERROR) {main_status|=STATUS_DS_ERR;}
				if (main_status&STATUS_DS_ERR) {OUT_ALL_OFF();flags=FLG_STOP_MAIN;}

				room_last_err=ds1820_start(ROOM);
				heater_last_err=ds1820_start(HEATER);
				radiator_last_err=ds1820_start(RADIATOR);
			}
			display();
		}
	}

	return 0;
}

ISR(INT1_vect){
	sec_flag++;
	TCNT1=0;
}

ISR(TIMER1_COMPA_vect){
	//TODO CLOCK ERROR
	//set_err_clock();
	sec_flag++;
}
